#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
if [ -f /etc/os-release ]; then
   echo "Linux system."
elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
   echo "macOS system."
   if [ -f ~/.bash_profile ]; then
      source ~/.bash_profile
    fi
elif current_os_is_windows; then
   echo "Windows system."
else
   echo "Unknown OS"
fi

# APP_INSTALL_NAME="latentsync"
APP_TARGET_DIR_NAME="LatentSync"

echo "lmdprogress:3"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_conda_pytorch.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_run.sh"

export CURRENT_APP_PATH="${LMD_APPS_DIR}/${APP_TARGET_DIR_NAME}"
echo $CURRENT_APP_PATH
mkdir -p "$CURRENT_APP_PATH"

echo "lmdprogress:8"

if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

echo "lmdprogress:12"

export GIT_HOST=${GITHUB_PROXY}"https://github.com"
if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
  export GIT_REPO_URL="${GIT_HOST}/ssrsybz/LatentSync1.5-mac"
elif current_os_is_windows; then
  export GIT_REPO_URL="${GIT_HOST}/bytedance/LatentSync"
fi

export GIT_REPO_BRANCH="main"
export LOCAL_REPO_PATH="$CURRENT_APP_PATH"
export REPO_COMMIT_ID="7b380d6adde7aa23cba4a53bb15cd5cfb3c168e7"
sh "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/git_clone_and_fetch_all.sh"

echo "lmdprogress:20"

source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"


conda --version
echo "lmdprogress:25"
cd "$CURRENT_APP_PATH"

export CONDA_PREFIX="./venv"

if [ -d "$CONDA_PREFIX" ]; then
    echo "found ./venv. remove it. "
    rm -rf "$CONDA_PREFIX"
fi
# conda_create_env $CONDA_PREFIX python=3.10 -y
export PYTHON_VER_ENV=3.10
conda_create_env $CONDA_PREFIX python=$PYTHON_VER_ENV -y

echo "lmdprogress:30"

cd "$CURRENT_APP_PATH"

echo "install torch and ffmpeg"

function install_ffmpeg {
  source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_ffmpeg.sh"
}

function check_ffmpeg_and_install_win {
  PROGRAMS=("ffmpeg" "ffprobe")
  missing_programs=0

  for PROGRAM in "${PROGRAMS[@]}"; do
    if ! command -v ${PROGRAM} >/dev/null 2>&1; then
      $PROGRAM -v
      echo "$PROGRAM not found"
      missing_programs=1
    fi
  done

  if [ $missing_programs -eq 1 ]; then
    echo "need install ffmpeg and ffprobe。"
    install_ffmpeg
  else
    echo "ffmpeg and ffprobe exist"
  fi
}

if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
    source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_mac.sh"
    conda_run_conda_forge_install ffmpeg
elif current_os_is_windows; then
    # source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_win.sh"
    source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_torch_multi_method.sh"
    check_ffmpeg_and_install_win
    conda_run_pip_install "$GIT_HOST/Gourieff/Assets/raw/refs/heads/main/Insightface/insightface-0.7.3-cp310-cp310-win_amd64.whl"
fi

echo "lmdprogress:40"

conda_run_pip_install huggingface_hub xet modelscope

echo "lmdprogress:42"
conda_run_pip_install --upgrade packaging
echo "lmdprogress:43"

download_and_unzip_buffalo_l () {
  echo "install buffalo_l"
  source "$LMD_BASE_INSTALL_SCRIPT_DIR/global/download_utils.sh"
  DOWNLOAD_FILE_NAME="$CURRENT_APP_PATH/buffalo_l.zip"
  BUFFALO_L_URL="$GIT_HOST/deepinsight/insightface/releases/download/v0.7/buffalo_l.zip"
  download_with_resume "$DOWNLOAD_FILE_NAME" "$BUFFALO_L_URL"

  cd "$CURRENT_APP_PATH"
  pwd
  MODELS_DIR="$CURRENT_APP_PATH/checkpoints/auxiliary/models/buffalo_l"
  mkdir -p "$MODELS_DIR"

  echo "unzip $DOWNLOAD_FILE_NAME to $MODELS_DIR"
  if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
    unzip -q "$DOWNLOAD_FILE_NAME" -d "$MODELS_DIR"
  elif current_os_is_windows; then
    # source "$LMD_BASE_INSTALL_SCRIPT_DIR/global/install_7z.sh"
    python "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/unzip_util.py" "$DOWNLOAD_FILE_NAME" "$MODELS_DIR"
    # 7zr x "$DOWNLOAD_FILE_NAME" -o"$MODELS_DIR" -y
  fi
}


install_requirements() {
  echo "modify requirements.txt and install them"

  rm -rf requirements-temp.txt
  if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
    # decord==0.6.0
    grep -vE 'torch==|torchvision==|download.pytorch.org|decord==|onnxruntime-gpu==|huggingface-hub==|gradio==' requirements.txt > requirements-temp.txt
    conda_run_pip_install eva-decord==0.6.1 gradio==5.29.1
  elif current_os_is_windows; then
    # if command -v nvidia-smi &>/dev/null && command -v nvcc &>/dev/null; then
    # if command -v nvidia-smi &>/dev/null; then
      # echo "Both nvidia-smi and nvcc commands are available."
      echo "install onnxruntime."
      # conda_run_cmd conda install onnxruntime==1.21.0 -c conda-forge -y
      conda_run_pip_install onnxruntime==1.21.0
    # fi
    download_and_unzip_buffalo_l
    cd "$CURRENT_APP_PATH"
    # conda_run_cmd conda install mediapipe==0.10.21 -c conda-forge -y
    conda_run_pip_install mediapipe==0.10.18 chardet
    
    grep -vE 'torch==|torchvision==|download.pytorch.org|insightface==|onnxruntime-gpu==|huggingface-hub==|mediapipe==' requirements.txt > requirements-temp.txt
    
  fi

  cat ./requirements-temp.txt
  conda_run_pip_install -r ./requirements-temp.txt
}

cd "$CURRENT_APP_PATH"
install_requirements

echo "lmdprogress:70"

if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

echo "start download models"

install_models() {
  export TORCH_HOME="./tmp_torch_home"
  
  echo "lmdprogress:78"

  # these are for cpu
  conda_run_cmd modelscope download --model 'ByteDance/LatentSync-1.5' auxiliary/2DFAN4-cd938726ad.zip --local_dir 'checkpoints'
  conda_run_cmd modelscope download --model 'ByteDance/LatentSync-1.5' auxiliary/s3fd-619a316812.pth --local_dir 'checkpoints'
  conda_run_cmd modelscope download --model 'ByteDance/LatentSync-1.5' auxiliary/vgg16-397923af.pth --local_dir 'checkpoints'
  echo "lmdprogress:80"
  export TORCH_HOME="./tmp_torch_home"
  AUXILIARY_DIR="checkpoints/auxiliary"
  A_TARGET_DIR="$TORCH_HOME/hub/checkpoints"
  echo "create dir: $A_TARGET_DIR"
  mkdir -p "$A_TARGET_DIR"
  
  echo "copy files..."
  cp -f "$AUXILIARY_DIR/2DFAN4-cd938726ad.zip" "$A_TARGET_DIR"
  cp -f "$AUXILIARY_DIR/s3fd-619a316812.pth" "$A_TARGET_DIR"
  cp -f "$AUXILIARY_DIR/vgg16-397923af.pth" "$A_TARGET_DIR"

  # these are required
  conda_run_cmd modelscope download --model 'ByteDance/LatentSync-1.5' whisper/tiny.pt --local_dir 'checkpoints'
  echo "lmdprogress:90"

  conda_run_cmd modelscope download --model 'ByteDance/LatentSync-1.5' latentsync_unet.pt --local_dir 'checkpoints'

  echo "lmdprogress:95"
  
  export HF_HOME="./tmp_hf_home"
  if [ -n "$HF_ENDPOINT" ]; then
    export HF_HOME="$CURRENT_APP_PATH/tmp_hf_home_by_modelscope"
    export TRANSFORMERS_CACHE="./tmp_hf_home_by_modelscope/hub"
    export TRANSFORMERS_OFFLINE=1
    export HF_HUB_DISABLE_SYMLINKS=1
    conda_run_hf_dl_by_modelsople "stabilityai/sd-vae-ft-mse" stabilityai--sd-vae-ft-mse
  else 
    conda_run_hf_download stabilityai/sd-vae-ft-mse
  fi
  
}

install_models

echo "lmdprogress:100"
